#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <cstring>

int main(int argc, char* argv[]){
    // 检查命令行参数数量
    if(argc != 3){
        std::cerr << "Usage: " << argv[0] << " <ServerIP> <ServerPort>" << std::endl;
        return 1; // 参数错误返回 1
    }
    std::string ip = argv[1];
    int port = std::stoi(argv[2]);

    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        perror("socket");
        return 1;
    }

    // 准备服务器地址信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if(inet_pton(AF_INET, ip.c_str(), &server_addr.sin_addr) <= 0){
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        close(sockfd);
        return 1;
    }

    // 2. 连接服务器
    if(connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0){
        perror("connect");
        close(sockfd);
        return 1;
    }
    // 3. 数据接收
    char buf[1024] = {0}; // 接收缓冲区
    ssize_t bytes_received = recv(sockfd, buf, sizeof(buf) - 1, 0);
    if (bytes_received > 0) {
        buf[bytes_received] = '\0'; // 确保字符串以 null 结尾
        std::cout << "Received " << bytes_received << " bytes: " << buf << std::endl;
    } else if (bytes_received == 0) {
        std::cout << "Server closed the connection." << std::endl;
    } else {
        perror("recv");
    }

    // 4. 关闭连接
    close(sockfd);
}